import React, { useEffect, useRef } from "react";
import E from "wangeditor";
import AV from "leancloud-storage";
//讲文件资源对象转为base64
const getBase64 = (img: any, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

export interface IRichEditorProps {
  onChange: (html: string) => void;
  value: string;
}

export default function RichEditor(props: Partial<IRichEditorProps>) {
  let editRef = useRef<HTMLDivElement>(null);
  console.log("RichEditor组件", props);
  useEffect(() => {
    let editor = new E(editRef.current);
    editor.config.onblur = function (newHtml: string) {
      console.log("onblur", newHtml); // 获取最新的 html 内容
      props.onChange!(newHtml);
    };
    editor.config.focus = false;
    editor.config.excludeMenus = ["table", "video"]; //隐藏某些按钮
    //自定义图片上传
    editor.config.customUploadImg = function (
      resultFiles: any,
      insertImgFn: any
    ) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      console.log(resultFiles);
      getBase64(resultFiles[0], (base64) => {
        const file = new AV.File("react-img.png", { base64 }); // 构建LeanCloud文件上传对象
        file.save().then((res: any) => {
          let { url } = res.attributes;
          insertImgFn(url);
          // props.onChange!(url); //将图片链接给到表单
        });
      });
      // 上传图片，返回结果，将图片插入到编辑器中
    };

    editor.create();
    editor.txt.html(props.value); // 重新设置编辑器内容

    return () => {
      //这个函数会在此useEffect下次执行前执行
      editor.destroy();
    };
  }, [props.value]);
  return <div ref={editRef}></div>;
}
